<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="this.operator.operatorName"
    width="800px"
    top="10px"
    @close="cancel"
  >
    <el-steps :active="active" align-center>
      <el-step :title="$t('operator.verify')" description="" />
      <el-step :title="$t('operator.process')" description="" />
      <el-step :title="$t('operator.checkComplete')" description="" />
    </el-steps>

    <div v-if="active === 0" class="stepContainer">
      <el-input
        v-model="operatorCer"
        type="textarea"
        class="center"
        disabled
        :rows="21"
      />
      <!--      <el-button type="primary" icon="el-icon-download" maxlength="10" size="medium" @click="downloadCertHandle">{{$t('operator.downloadCertBtn')}}</el-button>-->

      <div
        style="
          border-top: 1px solid #edf2f9;
          padding-top: 10px;
          padding-right: 10px;
          text-align: right;
        "
      >
        <el-button v-if="isAuth('10400204.MANAGE')" type="danger" @click="rejectHandle">
          {{ $t("operator.checkFailed") }}
        </el-button>
        <el-button
          v-if="isAuth('10400204.MANAGE')"
          type="primary"
          :disabled="this.nextStepVisible"
          @click="nextStep"
          >{{ $t("operator.checkSuccess") }}
        </el-button>
      </div>
    </div>
    <div v-if="active === 1 && !reject">
      <el-form ref="form" label-position="top" :model="form" :rules="dataRule">
        <el-form-item :label="$t('operator.level')" prop="levelCode">
          <el-select
            v-model="form.levelCode"
            class="w-full"
            :placeholder="$t('operator.level')"
            clearable
          >
            <el-option
              v-for="item in levelList"
              :key="item.levelCode"
              :value="item.levelCode"
              :label="item.levelName"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('operator.leverExpireTimeTip')">
          <el-date-picker
            v-model="form.expireTime"
            style="width: 100%"
            type="date"
            value-format="timestamp"
            :placeholder="$t('operator.expireTimeTip')"
          />
        </el-form-item>
        <el-form-item :label="$t('operator.mapType')">
          <el-select v-model="form.mapType" class="w-full" @change="mapSelect">
            <el-option
              v-for="item in mapList"
              :key="item.mapType"
              :value="item.mapType"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('operator.mapKey')" prop="mapKey">
          <!--          <div>-->
          <!--            <el-tag-->
          <!--              size="small"-->
          <!--              style="cursor: pointer; margin-right: 10px"-->
          <!--              @click="defaultKeyClick"-->
          <!--            >-->
          <!--              {{ $t('operator.defaulTag') }}-->
          <!--            </el-tag>-->
          <!--          </div>-->
          <br />
          <div>
            <el-radio v-model="radio" label="1">{{ $t("operator.defaulTag") }}</el-radio>
          </div>
          <div class="ml-4">
            <el-radio v-model="radio" label="2">
              <el-input
                v-model="form.mapKey"
                :placeholder="$t('operator.mapKey')"
                maxlength="128"
                show-word-limit
                @blur="() => (form.mapKey = form.mapKey.trim())"
                clearable
              />
            </el-radio>
          </div>
        </el-form-item>
        <el-form-item :label="$t('customer.customerLabel')">
          <!--          <el-autocomplete-->
          <!--            class="inline-input"-->
          <!--            v-model="oaCustomerName"-->
          <!--            :fetch-suggestions="getOaCustomerList"-->
          <!--            :trigger-on-focus="false"-->
          <!--            @select="handleSelectOaCustomer"-->
          <!--            style="width: 100%"-->
          <!--          ></el-autocomplete>-->
          <div>
            <el-input v-model="form.oaCustomerName" readonly>
              <template #suffix>
                <el-button
                  style="font-size: 20px"
                  type="text"
                  icon="el-icon-user-solid"
                  @click="openOaCustomer"
              /></template>
              <!--              <template slot="append">-->
              <!--                <button type="primary" ></button>-->
              <!--              </template>-->
            </el-input>
          </div>
          <!--          <el-checkbox v-model="isOversea" style="margin-left: 20px">海外客户</el-checkbox>-->
        </el-form-item>
        <el-form-item :label="$t('operator.payment_cert')" style="">
          <div style="position: relative">
            <el-upload
              ref="upload"
              action="#"
              accept=".crt"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :file-list="fileList"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button size="small" type="primary"
                  >{{ $t("operator.uploadFile") }}
                </el-button></template
              >
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('operator.payment_cert_tip')"
                placement="top"
              >
                <i class="el-icon-question cursor-pointer ml-2 text-gray-500"></i>
              </el-tooltip>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" style="margin-bottom: 20px">
          <el-input
            v-model="form.reason"
            type="textarea"
            :placeholder="$t('operator.checkSuccessTip')"
            maxlength="256"
            show-word-limit
            :autosize="{ minRows: 4, maxRows: 10 }"
          />
        </el-form-item>
      </el-form>

      <div
        style="
          display: flex;
          border-top: 1px solid #edf2f9;
          padding-top: 10px;
          padding-right: 10px;
          flex-direction: row-reverse;
        "
      >
        <el-button
          :disabled="this.fileList.length <= 0"
          type="primary"
          :loading="uploadCerLoading"
          @click="submitUpload"
        >
          {{ $t("common.confirm") }}
        </el-button>
        <el-button text style="margin-right: 10px" @click="preStep"
          >{{ $t("common.back") }}
        </el-button>
      </div>
    </div>
    <div v-if="active === 1 && reject" style="text-align: center" class="stepContainer">
      <el-form
        ref="rejectform"
        class="center"
        size="small"
        :model="form"
        :rules="dataRule"
      >
        <el-form-item prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            class="center"
            :placeholder="$t('operator.checkFailedReasonTip')"
            maxlength="256"
            required
            show-word-limit
            :autosize="{ minRows: 4, maxRows: 10 }"
            @blur="() => (form.reason = form.reason.trim())"
          />
        </el-form-item>
      </el-form>
      <div
        style="
          border-top: 1px solid #edf2f9;
          padding-top: 10px;
          padding-right: 10px;
          text-align: right;
        "
      >
        <el-button v-show="this.backVisible" text @click="preStep"
          >{{ $t("common.back") }}
        </el-button>
        <el-button type="primary" :loading="rejectLoading" @click="rejectConfirm"
          >{{ $t("common.confirm") }}
        </el-button>
      </div>
    </div>
    <div v-if="active === 2" class="stepContainer">
      <span style="font-size: 25px; color: #5daf34; margin: 10%"
        >{{ $t("operator.checkComplete") }}!</span
      >
    </div>
    <oa-customer-list
      v-if="oaCustomerListVisible"
      ref="oaCustomerList"
      @close="closeOaCustomerList"
    />
  </el-dialog>
</template>
<script>
import { downloadCert, examineOperator, checkOperator } from "@/api/operator";
// import http from '@/utils/httpRequest'
import { getMapList } from "@/utils";
import OaCustomerList from "./oa-customer-list";
import { getSystemMenuList } from "@/api/system-menu";
import { isAuth } from "@/utils";
export default {
  components: {
    OaCustomerList,
  },
  data() {
    return {
      rejectLoading: false,
      nextStepVisible: false,
      oaCustomerListVisible: false,
      backVisible: true,
      reject: false,
      active: 0,
      radio: "1",
      fileList: [],
      levelList: [],
      operatorCer: "",
      operator: {},
      form: {
        reason: "",
        levelCode: "STANDARD_LEVEL",
        expireTime: null,
        mapType: "MAP_BOX",
        mapKey: "",
        oaCustomerName: "",
        oaCustomerCode: "",
      },
      osCustomerList: "",
      isOversea: false,
      uploadCerLoading: false,
      mapList: [],
      dataRule: {
        mapType: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        reason: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
        // mapKey: [
        //   {
        //     required: true,
        //     message: this.$t('common.nullInputTip'),
        //     trigger: 'blur'
        //   }
        // ],
        levelCode: [
          {
            required: true,
            message: this.$t("common.nullInputTip"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // this.levelList = this.$t('operator.level_list')
    let params = {
      characterCode: "",
      levelCode: "",
      pageNo: 1,
      pageSize: 100,
    };
    getSystemMenuList(params)
      .then((res) => {
        this.levelList = res.data;
      })
      .catch((e) => {
        this.$confirmError(e);
      });
  },
  methods: {
    init(row) {
      console.log(new Date().getTimezoneOffset());
      this.rejectLoading = false;
      this.mapList = getMapList();
      this.operator = row;
      if (this.operator.operatorCertId === null) {
        this.backVisible = false;
        this.nextStepVisible = true;
      }
      this.form.mapType =
        this.operator.mapType === null ? this.form.mapType : this.operator.mapType;
      this.form.mapKey =
        this.operator.mapKey === null ? this.form.mapKey : this.operator.mapKey;
      this.downloadCertHandle();
    },
    mapSelect() {
      this.form.mapKey = "";
    },
    defaultKeyClick() {
      if (this.form.mapType === "MAP_BOX") {
        this.form.mapKey = this.mapList[0].mapKey;
      } else if (this.form.mapType === "GOOGLE") {
        this.form.mapKey = this.mapList[1].mapKey;
      } else if (this.form.mapType === "BAIDU") {
        this.form.mapKey = this.mapList[2].mapKey;
      }
    },
    cancel() {
      this.$emit("update:model-value", false);
    },
    nextStep() {
      this.active++;
    },
    preStep() {
      this.reject = false;
      this.active--;
    },
    rejectHandle(id) {
      this.reject = true;
      this.form.reason = "";
      this.nextStep();
    },
    rejectConfirm() {
      const params = {
        operatorId: this.operator.operatorId,
        remark: this.form.reason,
        operatorCerId: this.operator.operatorCertId,
        operatorCerStatus: 3,
        levelCode: "STANDARD_LEVEL",
      };
      this.$refs["rejectform"].validate((valid) => {
        if (valid) {
          this.rejectLoading = true;
          examineOperator(params)
            .then((data) => {
              this.$message({
                type: "success",
                message: this.$t("operator.checkComplete"),
              });
              this.$emit("refreshDataList");
              this.rejectLoading = false;
              this.nextStep();
            })
            .catch((err) => {
              this.rejectLoading = false;
              this.$confirmError(err);
            });
        }
      });
    },
    submitUpload() {
      console.log("oaCustomerCode:" + this.form.oaCustomerCode);
      console.log("oaCustomerName:" + this.form.oaCustomerName);
      if (this.radio === "2" && this.form.mapKey === "") {
        this.$confirm(this.$t("operator.map_not_null"), this.$t("page.tip"), {
          confirmButtonText: this.$t("page.confirm"),
          cancelButtonText: this.$t("page.cancel"),
          type: "warning",
        });
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.oaCustomerCode === "" || this.form.oaCustomerName === "") {
            this.$confirm(this.$t("operator.oaInfoIsNullConfirm"), "", {
              confirmButtonText: this.$t("common.confirm"),
              cancelButtonText: this.$t("common.cancel"),
              type: "warning",
            }).then(() => {
              this.examineOperatorHandle();
            });
          } else {
            this.examineOperatorHandle();
          }
        }
      });
    },
    handleRemove(file, fileList) {
      fileList.shift();
      this.fileList = fileList;
    },
    handlePreview(file) {
      console.log(file);
    },
    examineOperatorHandle() {
      this.uploadCerLoading = true;
      const formData = new FormData();
      console.log(this.fileList);
      formData.append("file", this.fileList[0].raw);
      checkOperator(this.operator.operatorCertId, formData)
        .then((res) => {
          console.log(res);
          const params = {
            operatorCerId: this.operator.operatorCertId,
            operatorId: this.operator.operatorId,
            remark: this.form.reason,
            operatorCerStatus: 1,
            levelCode: this.form.levelCode,
            expireTime: this.form.expireTime,
            mapType: this.form.mapType,
            mapKey: this.radio === "1" ? null : this.form.mapKey,
            mapToken: this.form.mapToken,
            oaCustomerCode: this.form.oaCustomerCode,
            oaCustomerName: this.form.oaCustomerName,
            isDefaultMapKey: this.radio === "1",
          };
          examineOperator(params)
            .then((data) => {
              this.$message({
                type: "success",
                message: this.$t("operator.checkComplete"),
              });
              this.uploadCerLoading = false;
              this.$emit("refreshDataList");
              this.nextStep();
              this.nextStep();
            })
            .catch((e) => {
              this.uploadCerLoading = false;
              this.$confirmError(e);
              console.log(`err:${JSON.stringify(e)}`);
            });
        })
        .catch((data) => {
          console.log(data);
          this.$message.error(data.message);
          this.fileList = [];
          this.uploadCerLoading = false;
        });
    },
    openOaCustomer() {
      this.oaCustomerListVisible = true;
      this.$nextTick(() => {
        this.$refs.oaCustomerList.init();
      });
    },
    closeOaCustomerList(customer) {
      console.log(customer);
      this.form.oaCustomerName = customer.customerName;
      this.form.oaCustomerCode = customer.customerCode;
    },
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift();
      }
      this.fileList = fileList;
      console.log(this.fileList);
    },
    downloadCertHandle() {
      const operatorId = this.operator.operatorId;
      downloadCert(operatorId)
        .then((data) => {
          this.operatorCer = data;
        })
        .catch((err) => {
          this.$confirmError(err);
        });
    },
    isAuth,
  },
};
</script>
<style lang="scss" scoped>
.stepContainer {
  text-align: center;
  margin-bottom: 10px;
  margin: 10px auto;
}

.center {
  width: 80%;
  margin: 16px auto;
}
</style>
